package com.qintian.rainstorm.datasourcse.aspect;

import com.qintian.rainstorm.datasourcse.DataSourceNames;
import com.qintian.rainstorm.datasourcse.DynamicDataSource;
import com.qintian.rainstorm.datasourcse.annnotiaon.DataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @description: 数据源切面类
 * @author: taoxi
 * @create: 2018-12-04 14:20
 * 实现 Orderd接口 是 让其 优先与别的 加载 数值越小 级别越高
 **/
@Aspect
@Component
public class DataSourceAspect implements Ordered {
    protected org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public int getOrder() {
        return 1;
    }

    @Pointcut("@annotation(com.qintian.rainstorm.datasourcse.annnotiaon.DataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        DataSource ds = method.getAnnotation(DataSource.class);
        if(ds == null){
            DynamicDataSource.setDataSource(DataSourceNames.FIRST);
            logger.debug("set datasource is " + DataSourceNames.FIRST);
        }else {
            DynamicDataSource.setDataSource(ds.name());
            logger.debug("set datasource is " + ds.name());
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            logger.debug("clean datasource");
        }
    }


}
